package cn.yotta.user.core.web.controller.common;

import cn.yotta.user.api.params.login.BaseLoginRequest;
import cn.yotta.user.api.params.login.LoginByMobilePasswordRequest;
import cn.yotta.user.api.params.login.LoginByUsernamePasswordRequest;
import cn.yotta.user.api.params.user.UserFindByTokenRequest;
import cn.yotta.user.api.vo.TokenVo;
import cn.yotta.user.api.vo.UserVo;
import cn.yotta.user.core.server.service.LoginService;
import cn.yotta.user.core.web.iface.TokenStorageStrategy;
import cn.yotta.user.core.web.utils.ApiExecutor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * @author wyaoyao
 * @date 2022/11/8 9:51
 */
@Slf4j
@Api("用户基础登录服务")
@RestController
@RequestMapping("user/common/login")
public class LoginController {

    private final LoginService loginService;
    private final TokenStorageStrategy tokenStorageStrategy;

    public LoginController(LoginService loginService, TokenStorageStrategy tokenStorageStrategy) {
        this.loginService = loginService;
        this.tokenStorageStrategy = tokenStorageStrategy;
    }

    @ApiOperation("用户名密码登录")
    @PostMapping(value = "/usernameAndPassword")
    public TokenVo loginByPassword(@RequestBody LoginByUsernamePasswordRequest request) {
        return doLogin(request);
    }

    @ApiOperation("用户名密码登录")
    @PostMapping(value = "/mobileAndPassword")
    public TokenVo loginByPassword(@RequestBody LoginByMobilePasswordRequest request) {
        return doLogin(request);
    }


    @ApiOperation(hidden = true, value = "内部调用：根据token获取登录用户信息")
    @GetMapping(value = "/token")
    public UserVo getLoginUser(UserFindByTokenRequest request) {
        return ApiExecutor.execute(loginService::getLoginUser, request);
    }


    private TokenVo doLogin(BaseLoginRequest request) {
        final TokenVo token = ApiExecutor.execute(loginService::login, request);
        // 2 保存token
        tokenStorageStrategy.save(token);
        return token;
    }

}
